﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections;
using System.Net;
using System.IO;
using System.Windows.Threading;
using System.Threading;
using System.Windows.Media.Animation;

namespace HandScreen.Views
{
    /// <summary>
    /// Interaction logic for Restaurants.xaml
    /// </summary>
    public partial class RestaurantsView : UserControl, IScrollable, ISuspendable
    {
        public ArrayList foods;

        private int updateInterval;

        private Boolean canScrollUp;
        private Boolean canScrollDown;

        private int paintedRows;
        private bool alive;

        private Thread updater;
        
        public RestaurantsView()
        {
            alive = true;
            updateInterval = 1000;
            InitializeComponent();
            foods = new ArrayList();
            updater = new Thread(dataMineRestaurants);
            updater.Start();
        }

        private void dataMineRestaurants()
        {
            while (alive)
            {
                foods.Clear();
                downloadMenus();
                this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(
                    delegate()
                    {
                        updatePage();
                        Thread initialize = new Thread(initializeAfterData);
                        initialize.Start();
                    }
                ));
                try { Thread.Sleep(updateInterval); }
                catch (Exception e) { }
            }
        }

        private void initializeAfterData()
        {
            Thread.Sleep(500);
            this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(
                    delegate()
                    {
                        scrollToPosition(scrollContainer.HorizontalOffset, scrollContainer.VerticalOffset);
                    }
                ));
        }

        public void updatePage()
        {
            foodsGrid.Children.Clear();
            GC.Collect();
            int rowCounter = 0;
            Boolean backAlternator = true;
            foreach (FoodsClass food in foods)
            {
                Border background = new Border();
                if (backAlternator)
                    background.Background = Brushes.Bisque;
                else
                    background.Background = Brushes.LightGray;
                backAlternator = !backAlternator;
                foodsGrid.Children.Add(background);

                rowCounter++;

                if (rowCounter > paintedRows)
                {
                    RowDefinition newRow = new RowDefinition();
                    newRow.Height = GridLength.Auto;
                    foodsGrid.RowDefinitions.Add(newRow);
                }

                TextBlock restName = new TextBlock();
                restName.Text = food.name;
                restName.Style = (Style)FindResource("mealRestaurant");
                foodsGrid.Children.Add(restName);

                TextBlock foodName = new TextBlock();
                foodName.Text = food.food;
                foodName.TextWrapping = TextWrapping.Wrap;
                foodName.Style = (Style)FindResource("mealDish");
                foodsGrid.Children.Add(foodName);

                TextBlock price = new TextBlock();
                price.Text = food.price;
                price.Style = (Style)FindResource("mealPrice");
                foodsGrid.Children.Add(price);



                Grid.SetColumn(restName, 0);
                Grid.SetColumn(foodName, 1);
                Grid.SetColumn(price, 2);

                Grid.SetRow(background, rowCounter);
                Grid.SetColumnSpan(background, 3);

                Grid.SetRow(restName, rowCounter);
                Grid.SetRow(foodName, rowCounter);
                Grid.SetRow(price, rowCounter);

            }
            paintedRows = rowCounter;
        }

        private void downloadMenus()
        {
            String url = "http://www.lindholmen.se/sv/dagens-lunch";
            // Open a connection
            HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create(url);

            // You can also specify additional header values like 
            // the user agent or the referer:
            WebRequestObject.UserAgent = "LindholmenUniversityAgent";
            WebRequestObject.Referer = "http://www.chalmers.se/";

            // Request response:

            string PageContent;

            try
            {
                WebResponse Response = WebRequestObject.GetResponse();
                
                // Open data stream:
                Stream WebStream = Response.GetResponseStream();

                // Create reader object:
                StreamReader Reader = new StreamReader(WebStream);

                // Read the entire stream content:
                PageContent = Reader.ReadToEnd();

                // Cleanup
                Reader.Close();
                WebStream.Close();
                Response.Close();
            }
            catch (Exception e)
            {
                PageContent = "Error in parsing webpage!";
            }

            // print the downloaded page
            // Console.WriteLine("{0}", PageContent);

            // parse the page
            int index1 = PageContent.IndexOf("views-field views-field-field-computed-restaurant-value", 0);
            int index2 = 0;
            String temp = "";

            // convert the ' characters to their proper look
            PageContent = PageContent.Replace("&#039;", "'");
            PageContent = PageContent.Replace("<strong>", "'");
            PageContent = PageContent.Replace("</strong>", "'");
            PageContent = PageContent.Replace("&quot;", "");

            // create the first entry
            FoodsClass tempFood = new FoodsClass();

            // loop through all restaurant entries
            while (true)
            {
                // locate start of a new restaurant line
                index1 = PageContent.IndexOf("views-field views-field-field-computed-restaurant-value", index1 + 1);
                if (index1 == -1) break;

                // create a new foods entry
                tempFood = new FoodsClass();
                foods.Add(tempFood);

                // locate next piece
                index1 = PageContent.IndexOf("<a href=", index1 + 1);
                // locate next piece
                index1 = PageContent.IndexOf(">", index1 + 1);
                // locate beginning and end of restaurant name
                index1++;
                index2 = PageContent.IndexOf("<", index1 + 1);
                // extract the restaurant name
                temp = PageContent.Substring(index1, index2 - index1);
                // print the restaurant name
                Console.WriteLine("{0}", temp);
                tempFood.name = temp;

                // locate next piece
                index1 = PageContent.IndexOf("views-field views-field-title active", index1 + 1);
                index1 = PageContent.IndexOf(">", index1 + 1);
                index1++;
                index2 = PageContent.IndexOf("<div class", index1 + 1);
                // extract the food description
                temp = PageContent.Substring(index1, index2 - index1);
                temp = temp.Trim();
                // print the food
                Console.WriteLine("{0}", temp);
                tempFood.food = temp;

                // locate next piece
                index1 = PageContent.IndexOf("views-field views-field-field-price-value", index1 + 1);
                index1 = PageContent.IndexOf(">", index1 + 1);
                index1++;
                index2 = PageContent.IndexOf("</td>", index1 + 1);
                // extract the food description
                temp = PageContent.Substring(index1, index2 - index1);
                temp = temp.Trim();
                // print the food
                Console.WriteLine("{0}", temp);
                tempFood.price = temp;
            }
        }

        public void scrollUp()
        {
            //scrollContainer.ScrollToVerticalOffset(scrollContainer.VerticalOffset - scrollContainer.ActualHeight * 0.80);
            scrollToPosition(scrollContainer.HorizontalOffset, scrollContainer.VerticalOffset - scrollContainer.ActualHeight * 0.80);
        }

        public void scrollDown()
        {
            //scrollContainer.ScrollToVerticalOffset(scrollContainer.VerticalOffset + scrollContainer.ActualHeight * 0.80);
            scrollToPosition(scrollContainer.HorizontalOffset, scrollContainer.VerticalOffset + scrollContainer.ActualHeight * 0.80);
        }

        private void scrollToPosition(double x, double y)
        {
            DoubleAnimation vertAnim = new DoubleAnimation();
            vertAnim.From = scrollContainer.VerticalOffset;
            vertAnim.To = y;
            vertAnim.DecelerationRatio = .2;
            vertAnim.Duration = new Duration(TimeSpan.FromMilliseconds(250));

            DoubleAnimation horzAnim = new DoubleAnimation();
            horzAnim.From = scrollContainer.HorizontalOffset;
            horzAnim.To = x;
            horzAnim.DecelerationRatio = .2;
            horzAnim.Duration = new Duration(TimeSpan.FromMilliseconds(300));

            Storyboard sb = new Storyboard();
            sb.Children.Add(vertAnim);
            sb.Children.Add(horzAnim);

            Storyboard.SetTarget(vertAnim, scrollContainer);
            Storyboard.SetTargetProperty(vertAnim, new PropertyPath(AniScrollViewer.CurrentVerticalOffsetProperty));
            Storyboard.SetTarget(horzAnim, scrollContainer);
            Storyboard.SetTargetProperty(horzAnim, new PropertyPath(AniScrollViewer.CurrentHorizontalOffsetProperty));

            sb.Begin();

            if (foodsGrid.ActualHeight - scrollContainer.ActualHeight <= 0)
            {
                topFade.Visibility = System.Windows.Visibility.Hidden;
                canScrollUp = false;
                bottomFade.Visibility = System.Windows.Visibility.Hidden;
                canScrollDown = false;
            }
            else
            {
                if (y <= 0)
                {
                    topFade.Visibility = System.Windows.Visibility.Hidden;
                    canScrollUp = false;
                }
                else
                {
                    topFade.Visibility = System.Windows.Visibility.Visible;
                    canScrollUp = true;
                }
                if (y >= foodsGrid.ActualHeight - scrollContainer.ActualHeight)
                {
                    bottomFade.Visibility = System.Windows.Visibility.Hidden;
                    canScrollDown = false;
                }
                else
                {
                    bottomFade.Visibility = System.Windows.Visibility.Visible;
                    canScrollDown = true;
                }
            }
        }

        public bool CanScrollUp()
        {
            return false;
            //return canScrollUp;
        }

        public bool CanScrollDown()
        {
            return false;
            //return canScrollDown;
        }

        public void suspend()
        {
            updater.Interrupt();
            alive = false;
        }
    }

    public class FoodsClass
    {
        public string name;
        public string food;
        public string price;
    }
}
